/**
 * Copyright (c) 2011-2012, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package protocol.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 *@module String工具类
 *@author 陈杰
*/
public class StringKit {
	
	private static SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");//时:分:秒:毫秒
	/**
	 * 判断字符串是否为空值
	 * NULL、空格均认为空值
	 * @param value
	 * @return
	 */
	public static boolean isEmpty(String value) {
		return null == value || "".equals(value.trim());
	}
	
	public static boolean isNotPrimaryKey(String value){
		String[] primaryKey = ConfigLoader.getStr("Ibatis.PrimaryKey").split(",");
		int i = 0;
		while(i<primaryKey.length){
			if(value.equals(primaryKey[i++])){return false;}
		}
		return true;
	}
	
	public static String noEmpty(String value){
		if(isEmpty(value)){
			return "";
		}
		return value;
	}
 
	/**
	 * 转换成Integer类型
	 * @param String value
	 * */
	public static Integer toInteger(String value){
		return isEmpty(value)?-1:Integer.parseInt(value);
	}

	/**
	 * 设置占位符
	 * 
	 * @param msg
	 * @param vars
	 * @return
	 */
	public static String setParameters(String msg, String[] vars) {
		for (int i = 0; i < vars.length; i++) {
			msg = msg.replaceAll("\\{" + i + "\\}", vars[i]);
		}
		return msg;
	}
	
	/**
	 * 设置占位符
	 * @param String msg
	 * @param Map<String,Object> param
	 * @return
	 */
	public static String setParameters(String msg,Map<String,Object> param,boolean isFJ) {
		for(String s : param.keySet()){
			if(!isFJ)
				msg = msg.replace("#" + s +"#", param.get(s).toString().trim());
			else
				msg = msg.replace("#" + s +"#", "'"+param.get(s).toString().trim()+"'");
		}
		return msg;
	}
	
	/**
	 * 设置占位符
	 * @param String msg
	 * @param Map<String,Object> param
	 * @return
	 */
	public static String setParameters(String msg,Map<String,Object> param) {
		for(String s : param.keySet()){
			if(param.get(s) instanceof String){
				msg = msg.replace("#" + s +"#", "'"+param.get(s).toString().trim()+"'");
			}else if(param.get(s) instanceof Integer){
				msg = msg.replace("#" + s +"#", param.get(s).toString().trim());
			}
		}
		return msg;
	}
	
	/**
	 * 首字母变小写
	 */
	public static String firstCharToLowerCase(String str) {
		Character firstChar = str.charAt(0);
		String tail = str.substring(1);
		str = Character.toLowerCase(firstChar) + tail;
		return str;
	}
	
	/**
	 * 首字母变大写
	 */
	public static String firstCharToUpperCase(String str) {
		Character firstChar = str.charAt(0);
		String tail = str.substring(1);
		str = Character.toUpperCase(firstChar) + tail;
		return str;
	}
	
	/**
	 * 字符串为 null 或者为  "" 时返回 true
	 */
	public static boolean isBlank(String str) {
		return str == null || "".equals(str.trim()) ? true : false;
	}
	
	/**
	 * 字符串不为 null 而且不为  "" 时返回 true
	 */
	public static boolean notBlank(String str) {
		return str == null || "".equals(str.trim()) ? false : true;
	}
	
	/**
	 * 非空，非Null判断
	 * */
	public static boolean notBlank(String... strings) {
		if (strings == null)
			return false;
		for (String str : strings)
			if (str == null || "".equals(str.trim()))
				return false;
		return true;
	}
	
	/**
	 * 非空判断
	 * */
	public static boolean notNull(Object... paras) {
		if (paras == null)
			return false;
		for (Object obj : paras)
			if (obj == null)
				return false;
		return true;
	}
	
	/**
	 * 字符串格式化
	 * */
	public static String toEncoder(String src){
		try {
			return URLEncoder.encode(src,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return src;
	}
	
	/**
	 * 字符串反格式化
	 * */
	public static String toDecode(String src){
		try {
			return URLDecoder.decode(src,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return src;
	}
	
	/**
	 * 获取不唯一的批次ID
	 * */
	public static String getBatchId(){
		UUID uuid = UUID.randomUUID();
		return uuid.toString().replace("-", "");
	}
	
	public static String parseMapToString(Map<String,String> map){
    	StringBuilder sb = new StringBuilder();
    	for(String key : map.keySet()){
    		sb.append(key).append(":").append(map.get(key)).append(" ");
    	}
    	return sb.toString();
    }
	/** 
     * 获得异常的堆栈信息，以字符串的形式返回。 
     */  
    public static String getExceptionInfo(Exception e){  
        StringWriter sw = new StringWriter();  
        PrintWriter pw = new PrintWriter(sw, true);  
        e.printStackTrace(pw);  
        pw.flush();  
        sw.flush();  
        return sw.toString();  
    }
	
    public static String byteToString(byte[] data, byte fmt) throws UnsupportedEncodingException {
		String content = "";
		switch (fmt) {
			case 0:
				content = new String(data);
				break;
			case 8:
				content = new String(data,"UTF-16BE");
				break;
			case 15:
				content = new String(data,"GBK");
				break;
			default:
				content = new String(data);
				break;
		}
		return content;
	}
    
	public static Map<String,String> parseStringToMap(String data){
		Map<String,String> returnMap = new HashMap<String,String>();
		String[] value = data.split(";");
		for(String s : value){
			String[] value2 = s.split("=");
			returnMap.put(value2[0], value2[1]);
		}
		return returnMap;
	}
	
	public static String getCurrentTime(){
		return sdf.format(new Date());
	}
	
	public static String convertBytesToString(byte bstr[]) {
        StringBuffer sb = new StringBuffer();
        try {
            for (int i = 0; i < bstr.length; i++) {
                if (Integer.toHexString(bstr[i] & 0xff).length() == 1) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(bstr[i] & 0xff)); // 转换成16进制的string格式
            }
        } catch (Exception e) {
        }
        return sb.toString();
    }
	
	
	public static String listToString(List<String> inList,String append){
		StringBuilder sendStr = new StringBuilder();
		for(int mobileIndex = 0;mobileIndex<inList.size();mobileIndex++){
			sendStr.append(inList.get(mobileIndex));
			if(mobileIndex<inList.size()-1 && append!=null) sendStr.append(append);
		}
		return sendStr.toString();
	}
	
	public static String listToString(String[] inList,String pres,String append){
		StringBuilder sendStr = new StringBuilder();
		for(int mobileIndex = 0;mobileIndex<inList.length;mobileIndex++){
			sendStr.append(pres).append(inList[mobileIndex]).append(pres);
			if(mobileIndex<inList.length-1 && append!=null) sendStr.append(append);
		}
		return sendStr.toString();
	}
}




